package com.ljh.bigevent.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.InputStream;

public class AliOssUtil {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private static final String END_POINT = "https://oss-cn-beijing.aliyuncs.com";
    // 直接设置AccessKey和Secret
    private static final String ACCESS_KEY_ID = "LTAI5tFRZiFkvGiBqoiWfE73";
    private static final String ACCESS_KEY_SECRET= "hLOjWPl6fqzXNBss8VFQVBKyGJfyhy";
    // 填写Bucket名称
    private static final String BUCKET_NAME = "ljh-bigevent";

    public static String uploadFile(String objectName, InputStream in) throws Exception {
        // 填写Object完整路径
        // String objectName = "001.png";
        // 填写本地文件的完整路径（必须包含具体文件名）
        /*String filePath = "C:\\Users\\ASUS\\Desktop\\bigevent\\微信图片编辑_20240605093259.jpg";*/
        // 创建OSSClient实例（简化版，不需要配置region和signature version）
        OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        String url="";
        try {
            /*InputStream inputStream = new FileInputStream(filePath);*/
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, in);
            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            url= "https://" + BUCKET_NAME + "." + END_POINT.replace("https://", "") + "/" + objectName;
            System.out.println("文件上传成功！ETag: " + result.getETag());
        } catch (OSSException oe) {
            System.out.println("OSS异常:");
            System.out.println("错误信息: " + oe.getErrorMessage());
            System.out.println("错误码: " + oe.getErrorCode());
            System.out.println("请求ID: " + oe.getRequestId());
            System.out.println("主机ID: " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("客户端异常:");
            System.out.println("错误信息: " + ce.getMessage());
        } catch (Exception e) {
            System.out.println("其他异常:");
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
